<?php
	class StaffModel extends CI_Model {
		// 表名
		static $roleTable = "school_role";
		static $coachTable = "school_coach";
		static $teacherTable = "school_user";
		static $classTable = "school_class";
		static $gradeTable = "school_grade";

	    public function __construct() {
	        parent::__construct();
	    }
	    
	    // 获取角色信息
	    public function get_role_info($roleId){
	    	$this->db->where("id", $roleId);
	    	return $this->db->get(self::$roleTable)->row_array();
	    }

	    // 获取角色列表
	    public function get_role_list($schoolId){
	    	$this->db->order_by("id ASC");
	    	$this->db->where("school_id", $schoolId);
	    	$this->db->where("is_delete", 0);
	    	return $this->db->get(self::$roleTable)->result_array();
	    }

	    // 根据角色id，获取子角色
	    public function get_sub_role_by_id($roleId){
	    	$this->db->where("role_parent_id", $roleId);
	    	$this->db->where("is_delete", 0);

	    	return $this->db->get(self::$roleTable)->result_array();
	    }

	    // 获取权限菜单数据源
	    public function get_role_tree_datasource($schoolId, $showAction = true){
	    	// 获取角色树状图
	        $roleDatasource = array();
	        $roleList = $this->get_role_list($schoolId);
	        foreach($roleList as $role) {
	            $roleId = $role['id'];
	            $rolePid = $role['role_parent_id'];
	            $roleTree = $role['role_parent_tree'];
	            // 菜单操作
	            $roleEditAction = '<a href="javascript:;" class="role-edit green"><i class="fa fa-pencil bigger-120"></i> 修改</a>';
	            $roleDeleteAction = '<a href="javascript:;" class="role-delete red"><i class="fa fa-trash-o bigger-120"></i> 删除</a>';
	            $roleAddSubAction = '<a href="javascript:;" class="role-add-sub blue"><i class="fa fa-plus bigger-120"></i> 添加下级</a>';
	            $roleName = '<span>'. $role['role_name'] .'</span>';
	            // 关系菜单
	            $tree['text'] = $showAction ? $roleName. $roleDeleteAction. $roleEditAction. $roleAddSubAction : $roleName;
	            $tree['type'] = 'item';
	            $tree['attr'] = array("id" => $roleId);
	            $tree['additionalParameters']['children'] = array();

	            // 根据关系树，生成下级关系
	            if($roleTree) {
	                $treeArray = explode(",", $roleTree);
	                $leaveStr = "";
	                foreach($treeArray as $parentId) {
	                    if($parentId == 0) continue;
	                    $leaveStr .= "['label_{$parentId}']['additionalParameters']['children']";
	                }

	                // 将上级设置为目录
	                $parentItemStr = substr($leaveStr, 0, strrpos($leaveStr, "['additionalParameters']['children']"));
	                eval("\$roleDatasource{$parentItemStr}['type'] = 'folder';");
	                // 包含到上级角色
	                eval("\$roleDatasource{$leaveStr}['label_'. \$roleId] = \$tree;");
	            } else {
	                $roleDatasource['label_'. $roleId] = $tree;
	            }
	        }
	        return json_encode($roleDatasource);
	    }

	    // 根据角色id，获取权限id
	    public function get_menu_id_by_role_id($roleIdSet){
	    	$roleIdSet = $roleIdSet ? $roleIdSet : 0;

	    	$this->db->where("id IN ({$roleIdSet})");
	    	$roleList = $this->db->get(self::$roleTable)->result_array();
	    	// 获取权限集合
	    	$idArray = array();
	    	foreach($roleList as $role) {
	    		$menuArray = explode(",", $role['role_menu']);
	    		$idArray = array_merge($idArray, $menuArray);
	    	}
	    	sort($idArray);

	    	return count($idArray) ? implode(",", $idArray) : 0;
	    }

	    // 根据角色id，获取角色名称
	    public function get_role_by_role_set($roleIdSet){
	    	$roleIdSet = $roleIdSet ?: 0;

			$this->db->where("id IN ({$roleIdSet})");
			// 过滤已删除
			$this->db->where("is_delete", 0);
	    	$roleList = $this->db->get(self::$roleTable)->result_array();
	    	// 获取权限集合
	    	$nameArray = array();
	    	foreach($roleList as $role) $nameArray[] = $role['role_name'];
	    	return $nameArray;
		}
		
		// 根据学校id和角色名称，获取角色id
		public function get_role_id_by_name($schoolId, $roleName){
			$this->db->where(array(
				'school_id' => $schoolId,
				'role_name' => $roleName
			));
			$this->db->select('id');
			return $this->db->get(StaffModel::$roleTable)->row_array();
		}

	    // 获取执教关系信息
	    public function get_coach_info($coachId){
	    	$this->db->where("id", $coachId);
	    	return $this->db->get(self::$coachTable)->row_array();
	    }

	    // 获取执教关系列表
	    public function get_coach_list($params){
            $coachTable = TABLE_PREFIX . self::$coachTable;
			$teacherTable = TABLE_PREFIX . self::$teacherTable;
			// $classTable = TABLE_PREFIX . self::$classTable;
			// $gradeTable = TABLE_PREFIX . self::$gradeTable;

			// $where = " LEFT JOIN {$teacherTable} ON {$teacherTable}.id = {$coachTable}.teacher_id LEFT JOIN {$classTable} ON {$classTable}.id = {$coachTable}.class_id
			// LEFT JOIN {$gradeTable} ON {$gradeTable}.id = {$classTable}.grade_id WHERE {$coachTable}.is_delete = 0 AND {$teacherTable}.is_delete = 0 AND {$classTable}.is_delete = 0 AND {$gradeTable}.is_delete = 0 ";
			$where = " LEFT JOIN {$teacherTable} ON {$teacherTable}.id = {$coachTable}.teacher_id WHERE {$coachTable}.is_delete = 0 AND {$teacherTable}.is_delete = 0 ";
			
			// 学校id
			if(isset($params['schoolId'])) $where .= " AND {$coachTable}.`school_id`='{$params['schoolId']}'";
			// 校区id
			if(isset($params['campusId'])) $where .= " AND {$coachTable}.`campus_id`='{$params['campusId']}' ";
			// 教师id
			if(isset($params['teacherId'])) $where .= " AND {$teacherTable}.`id` = '{$params['teacherId']}'";
			// 教师名称
			if(isset($params['teacherRealname'])) $where .= " AND {$teacherTable}.`realname` LIKE '%{$params['teacherRealname']}%'";
			// 执教角色
			if(isset($params['coachType'])) $where .= " AND {$coachTable}.`coach_type` = '{$params['coachType']}'";
			// 排除某种角色
			if(isset($params['notCoachType'])) $where .= " AND {$coachTable}.`coach_type` != '{$params['notCoachType']}'";
			if(isset($params['subjectId'])) {
				$where .= " AND FIND_IN_SET('{$params['subjectId']}', {$coachTable}.`subject_ids`)";
			}else {
				if(isset($params['subjectIdSet']) && $params['subjectIdSet']) {
					$idArr = explode(',', $params['subjectIdSet']);
					$str = ' AND (0';
					foreach($idArr as $id) {
						$str .= " OR FIND_IN_SET('{$id}', {$coachTable}.`subject_ids`)";
					}
					$str .= ' )';
					$where .= $str;
				}
			}
			// 传班级id，就不用处理年级id
			// if(isset($params['classId'])) {
			// 	$where .= " AND {$coachTable}.`class_id`='{$params['classId']}'";
			// } else {
			// 	if(isset($params['classSet'])) {
			// 		if($params['classSet'] === 0 || $params['classSet'] === '0') {
			// 			// 年级不存在班级
			// 			$where .= ' AND 0';
			// 		} else {
			// 			$classIdArr = explode(',', $params['classSet']);
			// 			$str = ' AND (0';
			// 			foreach($classIdArr as $classId) {
			// 				$str .= " OR  {$coachTable}.`class_id` = '{$classId}'";
			// 			}
			// 			$str .= ' )';
			// 			$where .= $str;
			// 		}
			// 	}
			// }
			// 改成班级多选
			if(isset($params['classId'])) {
				$where .= " AND FIND_IN_SET('{$params['classId']}', {$coachTable}.`class_ids`)";
			} else {
				if(isset($params['classSet'])) {
					if($params['classSet'] === 0 || $params['classSet'] === '0') {
						// 年级不存在班级
						$where .= ' AND 0';
					} else {
						$classIdArr = explode(',', $params['classSet']);
						$str = ' AND (0';
						foreach($classIdArr as $classId) {
							$str .= " OR FIND_IN_SET('{$classId}', {$coachTable}.`class_ids`)";
						}
						$str .= ' )';
						$where .= $str;
					}
				}
			}
			// 年级id
			if(isset($params['gradeId'])) $where .= " AND {$coachTable}.`grade_id` = '{$params['gradeId']}'";
			// 排序
			if(isset($params['orderBy'])) {
				// $orderSql = ' ORDER BY ' . $params['orderBy'];
			} else {
				$orderSql = " ORDER BY {$coachTable}.createtime DESC";
			}
			// 分页
			if(isset($params['pageStart']) && isset($params['pageSize'])) {
				$limitSql = ' LIMIT ' . $params['pageStart']. ',' . $params['pageSize'];
			} else {
				$limitSql = '';
			}
			$mainSql = "SELECT {$coachTable}.*,{$teacherTable}.realname FROM {$coachTable}" . $where . $orderSql . $limitSql;
			$query = $this->db->query($mainSql);
			$coachList = $query->result_array();
			if(isset($params['getRowNumber'])) {
				return count($coachList);
			} else {
				return $coachList;
			}
			return $this->db->get(self::$coachTable)->result_array();
		

		}
		
		// 执教关系，获取某个班级的班主任
		public function get_master_coach_by_class($classId) {
			// 过滤已删除
			$this->db->where('is_delete', 0);

			$this->db->where("FIND_IN_SET('{$classId}', `class_ids`)");
			$this->db->where('coach_type', COACH_TYPE_MASTER);
	    	return $this->db->get(self::$coachTable)->row_array();
		}
		// 执教关系，获取某个班级的班主任（支持多个班主任）
		public function get_master_coachs_by_class($classId) {
			// 过滤已删除
			$this->db->where('is_delete', 0);

			$this->db->where("FIND_IN_SET('{$classId}', `class_ids`)");
			$this->db->where('coach_type', COACH_TYPE_MASTER);
			return $this->db->get(self::$coachTable)->result_array();
		}

		// 执教关系，获取某个学校的班主任
		public function get_coach_by_school($schoolId, $campusId, $coachType) {
			// 过滤已删除
			$this->db->where('is_delete', 0);
			$this->db->where('school_id', $schoolId);
			$this->db->where('campus_id', $campusId);
			$this->db->where('coach_type', $coachType);
			return $this->db->get(self::$coachTable)->result_array();
		}
	}